const withCSS = require('@zeit/next-css')
const cssLoaderConfig = require('@zeit/next-css/css-loader-config')
const path = require('path')

const withLess = (nextConfig = {}) => {
  return Object.assign({}, nextConfig, {
    webpack(config, options) {
      if (!options.defaultLoaders) {
        throw new Error('This plugin is not compatible with Next.js versions below 5.0.0 https://err.sh/next-plugins/upgrade')
      }

      const { dev, isServer } = options
      const { cssModules, cssLoaderOptions, postcssLoaderOptions, lessLoaderOptions = {} } = nextConfig

      options.defaultLoaders.less = cssLoaderConfig(config, {
        extensions: ['less'],
        cssModules,
        cssLoaderOptions,
        postcssLoaderOptions,
        dev,
        isServer,
        loaders: [
          {
            loader: 'less-loader',
            options: lessLoaderOptions,
          },
          {
            loader: 'style-resources-loader',
            options: {
              patterns: [
                // 只有一条时也可以写成对象形式
                path.resolve(__dirname, 'styles/global.less'),
              ],
              // injector: 'append', // 如果在样式文件之后导入就加此行配置
            },
          },
        ],
      })

      config.module.rules.push({
        test: /\.less$/,
        use: options.defaultLoaders.less,
      })

      if (typeof nextConfig.webpack === 'function') {
        return nextConfig.webpack(config, options)
      }

      return config
    },
  })
}

module.exports = withLess(
  withCSS({
    // 禁用webpack5，因为css和less的共存配置会有问题
    webpack5: false,
  }),
)
